package com.thomas.framework.controller.admin;


import com.thomas.framework.entity.SysModel;
import com.thomas.framework.entity.SysUser;
import com.thomas.framework.service.ISysModelService;
import com.thomas.framework.service.ISysUserService;
import com.thomas.framework.service.impl.SysModelServiceImpl;
import com.thomas.framework.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * admin/WelcomeController
 * Created by taohj on 2014/4/8.
 */

@Controller

public class WelcomeAdminController extends AbstractControllser {


    @Autowired
    private ISysUserService userService;


    @Autowired
    private ISysModelService modelService;





    @RequestMapping({"admin"})
    public String index(HttpSession session) {

        SysUser user = getCurrentUser();

        if (user != null) {
            return "admin/sys/index";
        }
        return "admin/sys/login";
    }


    @ResponseBody
    @RequestMapping("getFunctinMenuTree")
    public String getFunctionMenuTree(HttpSession session) {
        SysUser user = getCurrentUser();
        List<SysModel> list = modelService.getTreeModel(user);
        return JsonUtil.toString(list);
    }

    @ResponseBody
    @RequestMapping("getFunctinMenu")
    public String getFunctionMenu() {

        return JsonUtil.toString(getCurrentUser().getFunctions());
    }


    @RequestMapping("admin/login")
    public String login(
            HttpServletRequest request,
            @RequestParam("userName") String userName,
            @RequestParam("password") String password/*,
            @RequestParam(value = "validateCode",required = false) String validateCode*/
    ) {



      /*  if (!validateCode.toLowerCase().equals( (request.getSession().getAttribute("validateCode") + "").toLowerCase())){
            request.getSession().setAttribute("message","Incorrect verification code.");
            return "forward:/admin";
        }*/

        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setPassword(password);


        user = userService.login(user);

        if (user == null) {
            request.setAttribute("message", "User name or password is incorrect");
            return "forward:/admin";
        }
        request.getSession().setAttribute("user", user);
        return "redirect:/admin";
    }


    @RequestMapping("admin/loginOut")
    public String loginOut(HttpSession session) {
        session.setAttribute("user", null);
        return "redirect:/admin";
    }


}
